<?php

namespace App\Http\Middleware;

use Illuminate\Support\Facades\Validator;
use App\Exceptions\JsonResponseException;
use Illuminate\Validation\Rule;

class LangCheck
{
    /**
     * 处理传入的请求
     *
     * @param  \Illuminate\Http\Request $request
     * @param \Closure                  $next
     *
     * @return mixed
     * @throws JsonResponseException
     */
    public function handle($request, \Closure $next)
    {
        // 参数校验
        $validator = Validator::make($request->all(), [
            'lang' => [
                'required',
                'string',
                Rule::in(['zh', 'en'])
            ],
        ], [
            'required' => ':attribute 不能为空',
            'string'   => ':attribute 必须为字符串',
            'in'       => ':attribute 超出可选值范围',
        ], [
            'lang' => '语言',
        ]);

        if ($validator->fails()) {
            throw new JsonResponseException((int)-2, $validator->errors()->first());
        }

        return $next($request);
    }
}
